package team.archai.nexus.boot.web.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import team.archai.nexus.boot.config.AuthProperties;
import team.archai.nexus.boot.tool.Tool;
import team.archai.nexus.boot.web.evaluators.AuthPermissionEvaluator;
import team.archai.nexus.boot.web.filters.JWTAuthorizationFilter;
import team.archai.nexus.boot.web.handlers.*;
import team.archai.nexus.boot.web.providers.AuthDetail;
import team.archai.nexus.boot.web.providers.AuthProvider;


import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: web security 权限注解
 * @author lishibin
 * @create: 2020-07-11 11:46
 **/
@Configuration
@EnableWebSecurity
//开启权限注解,默认是关闭的
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ConditionalOnProperty(name = "archai-nexus.auth.type", havingValue = "security")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义登录成功处理器
     */
    @Resource
    private AuthSuccessHandler authSuccessHandler;
    /**
     * 自定义登录失败处理器
     */
    @Resource
    private AuthFailureHandler authFailureHandler;
    /**
     * 自定义注销成功处理器
     */
    @Resource
    private AuthenticationHandler authenticationHandler;

    @Resource
    private LogoutHandler logoutHandler;
    /**
     * 自定义暂无权限处理器
     */
    @Resource
    private AcsDeniedHandler acsDeniedHandler;
    /**
     * 自定义未登录的处理器
     */
    @Resource
    private AuthPermissionEvaluator authPermissionEvaluator;
    /**
     * 自定义登录逻辑验证器
     */
    @Resource
    private AuthProvider authProvider;

    /**
     * 加密方式
     *
     * @Author Sans
     * @CreateTime 2019/10/1 14:00
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 注入自定义PermissionEvaluator
     */
    @Bean
    public DefaultWebSecurityExpressionHandler userSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(authPermissionEvaluator);
        return handler;
    }


    /**
     * 配置登录验证逻辑
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        //这里可启用我们自己的登陆验证逻辑
        auth.authenticationProvider(authProvider);
    }


    @Resource
    private AuthProperties authProperties;


    /**
     * 配置security的控制逻辑
     *
     * @Author lishibin
     * @CreateTime 2019/10/1 16:56
     * @Param http 请求
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        Customizer<FormLoginConfigurer<HttpSecurity>> customizerForm = (f) -> {
            f.loginProcessingUrl(authProperties.getLoginUrl());
            f.successHandler(authSuccessHandler);
            f.failureHandler(authFailureHandler);
            f.authenticationDetailsSource(new AuthDetail());
        };

        Customizer<LogoutConfigurer<HttpSecurity>> customizerLogout = (f) -> {
            f.logoutUrl(authProperties.getLogoutUrl());
            f.logoutSuccessHandler(logoutHandler);
        };
        LinkedHashMap<String, String> chains = authProperties.getFilterChain();
        List<String> antMatchers = chains.entrySet().stream().filter(e -> e.getValue().equals("anon")).map(Map.Entry::getKey).collect(Collectors.toList());
        HttpSecurity httpSecurity = http.formLogin(customizerForm);
        httpSecurity.logout(customizerLogout);
        http.authorizeRequests()
                // 不进行权限验证的请求或资源(从配置文件中读取)
                .antMatchers(Tool.toArray(antMatchers)).permitAll()
                // 其他的需要登陆后才能访问
                .anyRequest().authenticated()
                .and()
                // 配置未登录自定义处理类
                .httpBasic().authenticationEntryPoint(authenticationHandler)
                .and()
                // 配置没有权限自定义处理类
                .exceptionHandling().accessDeniedHandler(acsDeniedHandler)
                .and()
                // 开启跨域
                .cors()
                .and()
                // 取消跨站请求伪造防护
                .csrf().disable();
        // 基于Token不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用缓存
        http.headers().cacheControl();
        // 添加JWT过滤器
        http.addFilter(new JWTAuthorizationFilter(authenticationManager()));

    }
}
